package fr.neyb.wesb.core.data.io.impl.sb;

import java.io.IOException;
import java.io.Writer;

import fr.neyb.wesb.core.data.content.Record;
import fr.neyb.wesb.core.data.io.IOTextFormat;
import fr.neyb.wesb.core.data.io.RecordWriter;
import fr.neyb.wesb.core.data.io.impl.AbstractRecordIO;

public class SBRecordWriter extends AbstractRecordIO implements RecordWriter{

	private static class StringBufferWriter extends Writer {
		private final StringBuffer sb;

		public StringBufferWriter(StringBuffer sb) {
			this.sb = sb;
		}

		@Override
		public void write(char[] cbuf, int off, int len) {
			sb.append(cbuf, off, len);
		}

		@Override
		public void flush() {
		}

		@Override
		public void close() {
		}

	}

	private boolean open = false;
	private final IOTextFormat textFormat;
	private final StringBufferWriter sbw;

	public SBRecordWriter(StringBuffer sb, IOTextFormat textFormat) {
		super(textFormat.getDescriptor());
		this.textFormat = textFormat;
		sbw = new StringBufferWriter(sb);
	}

	@Override
	public boolean open() {
		boolean result = !open;
		open = true;
		return result;
	}

	@Override
	public boolean close() {
		boolean result = open;
		sbw.close();
		open = false;
		return result;
	}

	@Override
	public void write(Record toSave) {
		try {
			textFormat.Write(sbw, toSave);
		} catch (IOException e) {
			throw new AssertionError();
		}
	}
}
